<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PermissionWrapper from '../../components/PermissionWrapper.vue'

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 对话框状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: 'active',
  permissions: []
})

// 权限树数据
const permissionTree = ref([
  {
    id: 1,
    label: '系统管理',
    children: [
      { id: 11, label: '用户查看', value: 'user:view' },
      { id: 12, label: '用户创建', value: 'user:create' },
      { id: 13, label: '用户更新', value: 'user:update' },
      { id: 14, label: '用户删除', value: 'user:delete' },
      { id: 15, label: '角色查看', value: 'role:view' },
      { id: 16, label: '角色创建', value: 'role:create' },
      { id: 17, label: '角色更新', value: 'role:update' },
      { id: 18, label: '角色删除', value: 'role:delete' },
      { id: 19, label: '菜单管理', value: 'menu:view' }
    ]
  },
  {
    id: 2,
    label: '内容管理',
    children: [
      { id: 21, label: '内容查看', value: 'content:view' },
      { id: 22, label: '内容创建', value: 'content:create' },
      { id: 23, label: '内容更新', value: 'content:update' },
      { id: 24, label: '内容删除', value: 'content:delete' }
    ]
  },
  {
    id: 3,
    label: '系统设置',
    children: [
      { id: 31, label: '系统配置', value: 'system:settings' }
    ]
  }
])

// 模拟数据
const mockRoles = [
  {
    id: 1,
    name: '超级管理员',
    code: 'admin',
    description: '系统超级管理员，拥有所有权限',
    status: 'active',
    permissions: ['user:view', 'user:create', 'user:update', 'user:delete', 'role:view', 'role:create', 'role:update', 'role:delete', 'menu:view', 'content:view', 'content:create', 'content:update', 'content:delete', 'system:settings'],
    createTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    name: '编辑员',
    code: 'editor',
    description: '内容编辑员，可以管理内容',
    status: 'active',
    permissions: ['user:view', 'content:view', 'content:create', 'content:update'],
    createTime: '2024-01-02 10:00:00'
  },
  {
    id: 3,
    name: '普通用户',
    code: 'user',
    description: '普通用户，只能查看基本信息',
    status: 'active',
    permissions: ['user:view'],
    createTime: '2024-01-03 10:00:00'
  }
]

// 获取角色列表
const fetchRoles = async () => {
  loading.value = true
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = mockRoles
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 新增角色
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  isEdit.value = false
  dialogVisible.value = true
  resetForm()
}

// 编辑角色
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  isEdit.value = true
  dialogVisible.value = true
  Object.assign(roleForm, row)
}

// 删除角色
const handleDelete = async (row) => {
  if (row.code === 'admin') {
    ElMessage.warning('超级管理员角色不能删除')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(roleForm, {
    id: null,
    name: '',
    code: '',
    description: '',
    status: 'active',
    permissions: []
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (isEdit.value) {
      const index = tableData.value.findIndex(item => item.id === roleForm.id)
      if (index > -1) {
        Object.assign(tableData.value[index], roleForm)
      }
      ElMessage.success('更新成功')
    } else {
      const newRole = {
        ...roleForm,
        id: Date.now(),
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newRole)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 状态标签类型
const getStatusType = (status) => {
  return status === 'active' ? 'success' : 'danger'
}

onMounted(() => {
  fetchRoles()
})
</script>

<template>
  <div class="role-management">
    <!-- 操作区域 -->
    <div class="toolbar">
      <PermissionWrapper permission="role:create">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增角色
        </el-button>
      </PermissionWrapper>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        :data="tableData"
        :loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色编码" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <PermissionWrapper permission="role:update">
              <el-button type="primary" size="small" @click="handleEdit(row)">
                编辑
              </el-button>
            </PermissionWrapper>
            <PermissionWrapper permission="role:delete">
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDelete(row)"
                :disabled="row.code === 'admin'"
              >
                删除
              </el-button>
            </PermissionWrapper>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="resetForm"
    >
      <el-form
        :model="roleForm"
        ref="roleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" required>
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色编码" required>
          <el-input v-model="roleForm.code" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="roleForm.description" type="textarea" rows="3" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="roleForm.status" style="width: 100%">
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="权限配置">
          <el-tree
            :data="permissionTree"
            show-checkbox
            node-key="value"
            :default-checked-keys="roleForm.permissions"
            @check="handlePermissionChange"
          >
            <template #default="{ node, data }">
              <span>{{ data.label }}</span>
            </template>
          </el-tree>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 处理权限选择变化
const handlePermissionChange = (data, { checkedKeys }) => {
  roleForm.permissions = checkedKeys
}
</script>

<style scoped>
.role-management {
  padding: 0;
}

.toolbar {
  margin-bottom: 16px;
}

.table-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>